package com.yepit.translate.service;


import com.alibaba.excel.metadata.BaseRowModel;
import com.yepit.translate.dto.ExportInfo;
import com.yepit.translate.dto.ImportInfo;
import com.yepit.translate.dto.TransRespose;
import com.yepit.translate.util.excel.ExcelUtils;
import com.yepit.translate.util.translate.baidu.BaiduTransApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author qianlong
 * @description //TODO
 * @Date 2019/4/19 5:52 PM
 **/
@Service
public class TranslateService {

    public static final String DEFAULT_API_TYPE = "baidu";

    @Autowired
    private BaiduTransApi baiduTransApi;

    /**
     * 翻译excel文件
     *
     * @param uploadFile
     * @param rowModel
     * @param sheetNo
     * @param headLineNum
     */
    public void translateFileViaExcel(MultipartFile uploadFile, BaseRowModel rowModel, int sheetNo,
                                      int headLineNum, String apiType, HttpServletResponse response) throws Exception {
        if (uploadFile == null) {
            throw new Exception("文件不存在");
        }

        List<ExportInfo> exportInfoList = null;
        List<Object> dataList = ExcelUtils.readExcel(uploadFile, new ImportInfo(), sheetNo, headLineNum);
        if (dataList == null) {
            throw new Exception("文件内容为空");
        }
        exportInfoList = new ArrayList<>(dataList.size());
        for (Object obj : dataList) {
            ImportInfo importInfo = (ImportInfo) obj;
            String src = importInfo.getSrc();
            ExportInfo exportInfo = new ExportInfo();
            exportInfo.setSrc(src);
            TransRespose transRespose = baiduTransApi.getSingleTransResp(src, "en", "zh");
            if (transRespose != null && transRespose.getTransResult() != null) {
                exportInfo.setDst(transRespose.getTransResult().getDst());
            }
            exportInfoList.add(exportInfo);
        }

        String fileName = System.currentTimeMillis() + "";
        ExcelUtils.writeExcel(response, exportInfoList, fileName, "Result", new ExportInfo());
    }
}
